<?php
session_start();
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

$success = '';
$error = '';
$defaultSort = 1;

// 获取当前最大排序序号
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $stmt = $pdo->query("SELECT MAX(sort_order) AS max_sort FROM version_detail");
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $maxSort = $result['max_sort'] ?? 0;
    $defaultSort = (int)$maxSort + 1;
} catch (PDOException $e) {
    $defaultSort = 1;
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $versionCode = trim($_POST['version_code'] ?? '');
    $releaseDate = trim($_POST['release_date'] ?? '');
    $newFeatures = trim($_POST['new_features'] ?? '');
    $bugFixes = trim($_POST['bug_fixes'] ?? '');
    $sortOrder = (int)($_POST['sort_order'] ?? $defaultSort);

    if (empty($versionCode)) {
        $error = "版本号不能为空";
    } elseif (empty($releaseDate)) {
        $error = "发布日期不能为空";
    } elseif ($sortOrder <= 0) {
        $error = "排序序号必须是正整数";
    } else {
        try {
            $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $stmt = $pdo->prepare("SELECT id FROM version_detail WHERE sort_order = :sort");
            $stmt->execute([':sort' => $sortOrder]);
            if ($stmt->fetch()) {
                $error = "排序序号已存在，请更换其他序号";
            } else {
                $stmt = $pdo->prepare("INSERT INTO version_detail 
                                    (version_code, release_date, new_features, bug_fixes, sort_order)
                                    VALUES (:version, :date, :features, :fixes, :sort)");
                $stmt->execute([
                    ':version' => $versionCode,
                    ':date' => $releaseDate,
                    ':features' => $newFeatures,
                    ':fixes' => $bugFixes,
                    ':sort' => $sortOrder
                ]);

                header('Location: version.php?success=版本添加成功');
                exit;
            }

        } catch (PDOException $e) {
            $error = "添加失败：" . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增版本 - IT知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/common.css"> <!-- 引入统一样式 -->
</head>
<body>
    <div class="admin-container">
        <!-- 左侧侧边栏（与index.php完全一致） -->
        <aside class="admin-sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <i class="fas fa-cogs"></i>
                    <span>知识库管理</span>
                </div>
            </div>
            <ul class="nav-list">
                <li class="nav-item">
                    <a href="index.php" class="nav-link">
                        <i class="fas fa-home"></i>
                        <span>管理首页</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="article.php" class="nav-link">
                        <i class="fas fa-file-alt"></i>
                        <span>文章管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="category.php" class="nav-link">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="version.php" class="nav-link active">
                        <i class="fas fa-sync-alt"></i>
                        <span>版本管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="logout.php" class="nav-link">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>退出登录</span>
                    </a>
                </li>
            </ul>
        </aside>

        <!-- 右侧内容区 -->
        <main class="admin-content">
            <div class="content-wrapper">
                <div class="page-header">
                    <h1 class="page-title">新增版本记录</h1>
                    <a href="version.php" class="btn btn-outline">
                        <i class="fas fa-arrow-left"></i>返回列表
                    </a>
                </div>

                <?php if ($error): ?>
                    <div class="message message-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo $error; ?></span>
                    </div>
                <?php endif; ?>

                <div class="form-card">
                    <form method="post" action="version_add.php" class="version-form">
                        <!-- 版本号、日期、序号同行（使用统一的inline-fields类） -->
                        <div class="inline-fields">
                            <div class="form-group">
                                <label class="form-label" for="version_code">
                                    版本号 <span class="required">*</span>
                                </label>
                                <input type="text" id="version_code" name="version_code" class="form-control" 
                                    placeholder="如：1.0.2" value="<?php echo htmlspecialchars($_POST['version_code'] ?? ''); ?>">
                                <div class="form-hint">格式示例：1.0.0、2.1.3（主版本.次版本.修订号）</div>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="release_date">
                                    发布日期 <span class="required">*</span>
                                </label>
                                <input type="date" id="release_date" name="release_date" class="form-control" 
                                    value="<?php echo htmlspecialchars($_POST['release_date'] ?? date('Y-m-d')); ?>">
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="sort_order">
                                    排序序号 <span class="required">*</span>
                                </label>
                                <input type="number" id="sort_order" name="sort_order" class="form-control" 
                                    value="<?php echo htmlspecialchars($_POST['sort_order'] ?? $defaultSort); ?>" 
                                    min="1" 
                                    placeholder="序号越小越靠前">
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="form-label" for="new_features">新增功能</label>
                            <textarea id="new_features" name="new_features" class="form-textarea" 
                                placeholder="每行填写一项，如：1. 新增xxx功能"><?php echo htmlspecialchars($_POST['new_features'] ?? ''); ?></textarea>
                        </div>

                        <div class="form-group">
                            <label class="form-label" for="bug_fixes">修复问题</label>
                            <textarea id="bug_fixes" name="bug_fixes" class="form-textarea" 
                                placeholder="每行填写一项，如：1. 修复xxx问题"><?php echo htmlspecialchars($_POST['bug_fixes'] ?? ''); ?></textarea>
                        </div>

                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i>保存版本
                            </button>
                            <button type="reset" class="btn btn-outline">
                                <i class="fas fa-redo"></i>重置
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</body>
</html>